﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SQLHelper;
using System.Data.SqlClient;
using MessageBoxHelper;

namespace BBS
{
    public partial class Login : BasePage
    {
        protected void Page_Load (object sender, EventArgs e)
        {
            if ( !IsPostBack )
            {

            }
        }

        protected void btnLogin_Click (object sender, EventArgs e)
        {
            string pickName = this.txtPickName.Text;
            string pwd = this.txtPwd.Text;

            string queryStr = string.Format("SELECT * FROM ACCOUNT WHERE PICKNAME='{0}' AND PWD='{1}'", pickName, pwd);
            SQLHelperSingleton.TryQueryByDataReader(queryStr, this.QuerySuccess, this.QueryFail);
        }

        /// <summary>
        /// sql执行成功的代理
        /// </summary>
        /// <param name="reader"></param>
        private void QuerySuccess (SqlDataReader reader)
        {
            if ( reader.Read() )
            {
                string id = reader["ACCOUNT_ID"].ToString();
                string pickName = reader["PICKNAME"].ToString();
                int limit = int.Parse(reader["LIMIT"].ToString());

                //创建用户类对象,保存到session
                User user = new User(pickName, id, limit);
                this.Session["user"] = user;

                //用cookie保存该对象
                Response.Cookies["user"]["id"] = id;
                Response.Cookies["user"]["pickName"] = pickName;
                Response.Cookies["user"]["limit"] = limit.ToString();
                Response.Cookies["user"].Expires = DateTime.Now.AddDays(7);

                //跳转到上一页，如果没有就直接到主页
                if ( this.Session["retu"] != null )
                {
                    string url = this.Session["retu"].ToString();
                    this.RedirectTo(url);
                } else
                {
                    this.RedirectTo("Index.aspx");
                }
            } else
            {
                this.ExecuteJS("alert('账号或密码输入错误！');");
            }
        }

        /// <summary>
        /// sql执行失败的代理
        /// </summary>
        /// <param name="errMsg"></param>
        private void QueryFail (string errMsg)
        {
            this.ExecuteJS(string.Format("alert('{0}');", errMsg));
        }
    }
}